package com.example.controller;


import com.example.domain.dto.DepartmentDTO;
import com.example.domain.po.Department;
import com.example.service.HospitalDepartmentService;
import com.example.util.AliOSSUtils;
import com.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/hospitalDepartment")
public class HospitalDepartmentController {

    @Autowired
    private HospitalDepartmentService hospitalDepartmentService;

    @Autowired
    private AliOSSUtils aliOSSUtils;


    @Value("${file.path}")
    private String path;

    @PostMapping("/add")
    public Result<String> add(DepartmentDTO departmentDTO) throws IOException {
        //departmentDTO.setPhotopath(aliOSSUtils.upload(departmentDTO.getFile()));
        var oldFilename = departmentDTO.getFile().getOriginalFilename();
        int i = oldFilename.lastIndexOf(".");
        var suffix = oldFilename.substring(i);
        var newFilename = String.valueOf(UUID.randomUUID()) + suffix;
        var file = new File(path, newFilename);
        departmentDTO.getFile().transferTo(file);
        departmentDTO.setPhotopath(newFilename);
        hospitalDepartmentService.add(departmentDTO);
        return Result.success("添加成功");
    }


    @PostMapping("/update")
    public Result<String> update(DepartmentDTO departmentDTO) throws IOException {
        departmentDTO.setPhotopath(aliOSSUtils.upload(departmentDTO.getFile()));
        hospitalDepartmentService.update(departmentDTO);
        return Result.success("修改成功");
    }

    @GetMapping("/findAdd")
    public Result<List<Department>> findAdd(Integer hospitalId) {
        return hospitalDepartmentService.findAdd(hospitalId);
    }

    @GetMapping("/del")
    public Result<String> del(Integer hospitalId, Integer departmentId) {
        hospitalDepartmentService.del(hospitalId, departmentId);
        return Result.success("删除成功");
    }


}
